package com.example.onion.hxchat.fragment;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;


import com.example.onion.hxchat.activity.LoginActivity;
import com.example.onion.hxchat.activity.SearchFriendActivity;
import com.example.onion.hxchat.adapter.MyPagerAdapter;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.util.GsonUtil;
import com.example.onion.hxchat.util.HttpUtils;
import com.example.superyi.myteam.R;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.hyphenate.chat.EMClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;

/**
 * wc 主要的fragment了，也是最后要集成到项目MainActivity的fragment
 * 包含了三个fragment，如下
 * 消息InfoFragment，好友列表FriendFragment，通知列表NotificationFragment三个fragment
 * TODO 主要的fragment
 */
public class TabViewPagerFragment extends Fragment implements View.OnClickListener,ViewPager.OnPageChangeListener{

    private View view;

    private ViewPager vpager_four;
    private ImageView img_cursor;
    private TextView tv_one;
    private TextView tv_two;
    private TextView tv_three;

    private ArrayList<Fragment> listViews;
    private int offset = 0;//移动条图片的偏移量
    private int currIndex = 0;//当前页面的编号
    private int bmpWidth;// 移动条图片的长度
    private int one = 0; //移动条滑动一页的距离
    private int two = 0; //滑动条移动两页的距离
    private Toolbar mToolbar;
    private String TAG = "MainFragmentWc";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.tabviewpager_fragment_layout,container,false);
        initViews();
        return view;
    }



    //在Fragment中获取Toolbar
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        AppCompatActivity appCompatActivity= (AppCompatActivity) getActivity();
        Toolbar toolbar= (Toolbar) appCompatActivity.findViewById(R.id.main_fragment_wc_toolbar);
        appCompatActivity.setSupportActionBar(toolbar);
        ActionBar actionBar = appCompatActivity.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        super.onActivityCreated(savedInstanceState);
    }
//Fragment获取Toolbar获取menu
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.toolbar_main,menu);
        SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
        SearchView mSearchView = (SearchView) menu.findItem(R.id.info_search).getActionView();
        // Assumes current activity is the searchable activity
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
        //搜索框
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
            @Override
            public boolean onQueryTextSubmit(String query) {//String query提交的搜索内容
                Log.i(TAG,query);
                Intent intent = new Intent(getContext(), SearchFriendActivity.class);
                intent.putExtra("searchFriendUserName",query);
                startActivity(intent);
                Toast.makeText(getContext(),query,Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {//回调查询文本的更改。
                return false;
            }
        });
        super.onCreateOptionsMenu(menu, inflater);
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_toolbar_logout://退出登录的选项
                Log.d("InfoActivity", "退出登录");
                logout();
                break;
            default:
                break;
        }
        return true;
    }
    /**
     * 集成环信退出登录 EMClient.getInstance().logout(true)；
     * 顺便实现删除保存的登录的用户的账号，完成LoginActivity类说明的功能
     */
    private void logout()
    {
        //将空值的用户账户和密码保存，覆盖先前的数据实现清除账户数据，
        // 以便可以通过PassWordHelp能否获取数据判断用户登录状态
//        PassWordHelp.savePassword(getContext(),"","",false);
//        String accountId = PassWordHelp.readPassword(getContext())[0];
//        String pwd = PassWordHelp.readPassword(getContext())[1];
//        Log.e("INfoActivity","保存null之后获取的accountId"+accountId);
//        Log.e("INfoActivity","保存null之后获取的pwd"+pwd);
        EMClient.getInstance().logout(true);
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivity(intent);
        Toast.makeText(getContext(), "退出登录", Toast.LENGTH_SHORT).show();
    }

    private void initViews() {
        vpager_four = view.findViewById(R.id.vpager_four);
        tv_one = view.findViewById(R.id.tv_one);
        tv_two = view.findViewById(R.id.tv_two);
        tv_three = view.findViewById(R.id.tv_three);
        img_cursor = view.findViewById(R.id.test_img_cursor_wc);
        //下划线动画的相关设置：
        bmpWidth = BitmapFactory.decodeResource(getResources(), R.mipmap.line).getWidth();// 获取图片宽度
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = (screenW / 3 - bmpWidth) / 2;// 计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        img_cursor.setImageMatrix(matrix);// 设置动画初始位置
        //移动的距离
        one = offset * 2 + bmpWidth;// 移动一页的偏移量,比如1->2,或者2->3
        two = one * 2;// 移动两页的偏移量,比如1直接跳3


        //往ViewPager填充View，同时设置点击事件与页面切换事件
        listViews = new ArrayList<Fragment>();
        LayoutInflater mInflater = getLayoutInflater();
        listViews.add(new InfoFragment());
        listViews.add(new FriendFragment());
        listViews.add(new TeamNotificationFragment());
        vpager_four.setAdapter(new MyPagerAdapter(getChildFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,listViews));
        vpager_four.setCurrentItem(0);          //设置ViewPager当前页，从0开始算


        tv_one.setOnClickListener(this);
        tv_two.setOnClickListener(this);
        tv_three.setOnClickListener(this);
        vpager_four.addOnPageChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_one:
                vpager_four.setCurrentItem(0);
                break;
            case R.id.tv_two:
                vpager_four.setCurrentItem(1);
                break;
            case R.id.tv_three:
                vpager_four.setCurrentItem(2);
                break;
        }
    }

    @Override
    public void onPageSelected(int index) {
        Animation animation = null;
        switch (index) {
            case 0:
                if (currIndex == 1) {
                    animation = new TranslateAnimation(one, 0, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, 0, 0, 0);
                }
                break;
            case 1:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, one, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, one, 0, 0);
                }
                break;
            case 2:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, two, 0, 0);
                } else if (currIndex == 1) {
                    animation = new TranslateAnimation(one, two, 0, 0);
                }
                break;
        }
        currIndex = index;
        animation.setFillAfter(true);// true表示图片停在动画结束位置
        animation.setDuration(300); //设置动画时间为300毫秒
        img_cursor.startAnimation(animation);//开始动画
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }
}
